package com.sdhs.paas.gateway.util;

import java.io.Serializable;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.config.MemoryUnit;

public class AmeCacheUtil
{
  public static String POLICY_CACHE_NAME = "amePolicy";

  public static int POLICY_CACHE_EXPIRY = 30000;

  public static <T> void put(String cacheName, Serializable key, T value)
  {
    Element element = new Element(key, value);
    getCache(cacheName).put(element);
  }

  public static Element get(String cacheName, Serializable key) {
    return getCache(cacheName).get(key);
  }

  public static <T> T get(String cacheName, Serializable key, int expiry)
  {
    Element element = get(cacheName, key);
    if ((element == null) || (System.currentTimeMillis() - element.getLastUpdateTime() > expiry)) {
      return null;
    }
    return (T) element.getObjectValue();
  }

  public static CacheManager getEhcacheManager()
  {
    CacheManager cacheManager = (CacheManager)SpringContextUtil.getBean("ame-ehcacheManager");
    return cacheManager;
  }

  public static Cache getCache(String cacheName)
  {
    Cache cache = getEhcacheManager().getCache(cacheName);
    if (cache == null) {
      CacheConfiguration cacheConfiguration = new CacheConfiguration();
      cacheConfiguration.maxBytesLocalHeap(100L, MemoryUnit.MEGABYTES);
      cacheConfiguration.setTimeToLiveSeconds(0L);
      cacheConfiguration.setName(cacheName);
      cache = new Cache(cacheConfiguration);
      getEhcacheManager().addCache(cache);
    }
    return cache;
  }
}